package com.activeMq.producer.service;

import com.google.gson.Gson;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.jms.Destination;
import java.util.HashMap;
import java.util.Map;

@Service
public class ActviceMqSendService {
    private final JmsTemplate jmsTemplate;

    private final Destination destination = new ActiveMQQueue("ActviceMqQuere");
    private final Gson gson = new Gson();
    private final Map<String, Object> okMap = new HashMap<String, Object>() {{
        put("success", true);
    }};
    private final Map<String, Object> noMap = new HashMap<String, Object>() {{
        put("success", false);
    }};

    @Autowired
    public ActviceMqSendService(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    /**
     * 发送消息
     */

    public Map<String, Object> sendMessage(Map<String, Object> msgMap) {
        try {
            this.jmsTemplate.convertAndSend(destination, gson.toJson(msgMap));
            return okMap;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("发送ActiveMq消息失败:" + e.getMessage());
            noMap.put("message", e.getMessage());
            return noMap;
        }
    }

}
